package com.example.uithreaddemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView textView1;

    private TextView textView2;

    private TextView textView3;

    private TextView textView4;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView1 = findViewById(R.id.text_1);
        textView2 = findViewById(R.id.text_2);
        textView3 = findViewById(R.id.text_3);
        textView4 = findViewById(R.id.text_4);

        // 方法一，通过Handler的sendMessage
        new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Message message = new Message();
            message.what = 111;
            message.obj = "1阿巴阿巴";
            handler.sendMessage(message);
        }).start();

        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 111) {
                    textView1.setText(msg.obj.toString());
                }
            }
        };


        // 方法二，通过View的post
        new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            textView2.post(() -> {
                textView2.setText("2阿巴阿巴");
            });
        }).start();

        // 方法三，通过Activity的runOnUiThread
        new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                textView3.setText("3阿巴阿巴");
            });
        }).start();

        // 方法四，通过AsyncTask


    }
}